package com.naihe.anderson.sms.activity;

import java.util.Timer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.Geoloc;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.util.HttpUtil;

public class WebMapActivity extends Activity implements View.OnClickListener {
    private static final String MAP_URL = "file:///android_asset/map/map_cn.html";
    String GET_CENTER = "javascript:getCenter()";
    String UPDATE_IMG = "javascript:updateImg('location_arrows.png')";

    private Location mostRecentLocation;
    private WebView webView;
    boolean isMoved = false;
    private TextView tip;
    private String tipTemp = "";
    private ProgressBar progressBar;
    private ImageButton locationHere;
    private FrameLayout locaion_arrow_tips_ll;
    private int iAutoUpdateFrequency = 1000;
    LocationManager mLocationManager;
    
    NhSmsApp nhSmsApp;

//    private String sessionUid = "";
    Double lat, lon;
    int flag = 0;
    Timer timer1;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_for_android);
        
        nhSmsApp = (NhSmsApp) getApplication();
		nhSmsApp.setActivity(this);

        lat = getIntent().getDoubleExtra("lat", 30.251442);
        lon = getIntent().getDoubleExtra("lon", 120.172950);

        getLocation();
        setupWebView();
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        Button ok_btn = (Button) findViewById(R.id.ok_btn);
        Button back_btn = (Button) findViewById(R.id.back_btn);
        RelativeLayout control = (RelativeLayout) findViewById(R.id.control_id);
//        if (sessionUid != null) {
            ok_btn.setVisibility(View.VISIBLE);
            control.setVisibility(View.VISIBLE);
            webView.setOnTouchListener(new MapOnTouchListener());
//        }

        ok_btn.setOnClickListener(this);
        back_btn.setOnClickListener(this);

        tip = (TextView) findViewById(R.id.location_tips);
        progressBar = (ProgressBar) findViewById(R.id.location_load_progress);
        locaion_arrow_tips_ll = (FrameLayout) findViewById(R.id.locaion_arrow_tips_ll);
        locationHere = (ImageButton) findViewById(R.id.location_here);
    }

    class MapOnTouchListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            int action = motionEvent.getAction();
            switch (action) {
                case MotionEvent.ACTION_MOVE:
                    if (!isMoved) {
                        isMoved = true;
                        locaion_arrow_tips_ll.setVisibility(View.GONE);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (isMoved) {
                        isMoved = false;
                        TranslateAnimation animation = new TranslateAnimation(0, 0, 100, 0);
                        animation.setDuration(400);
                        animation.setFillAfter(true);
                        locationHere.startAnimation(animation);
                        locaion_arrow_tips_ll.setVisibility(View.VISIBLE);
                        progressBar.setVisibility(View.VISIBLE);
                        tip.setText("");
                        webView.loadUrl(GET_CENTER);
                    }
                    break;
            }
            return false;
        }
    }


    private void getLocation() {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, iAutoUpdateFrequency, 0,
                    locationListener);
            mostRecentLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
    }

    /**
     * Sets up the WebView object and loads the URL of the page *
     */
    private void setupWebView() {
//        if (sessionUid != null && mostRecentLocation != null) {
        if (mostRecentLocation != null) {
            lat = mostRecentLocation.getLatitude();
            lon = mostRecentLocation.getLongitude();
        }

        final String centerURL = "javascript:centerAt(" + lat + "," + lon + ")";
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        //Wait for the page to load then send the location information
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webView.loadUrl(centerURL);
                webView.loadUrl(GET_CENTER);

//                if (sessionUid == null) {
                    webView.loadUrl(UPDATE_IMG);
//                }
            }
        });
        webView.loadUrl(MAP_URL);
        webView.addJavascriptInterface(new JavaScriptInterface(), "Qingzhi");
    }


    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.ok_btn){
            Geoloc geoloc = new Geoloc();
            geoloc.setLat(lat);
            geoloc.setLon(lon);
            geoloc.setCountry(tipTemp);
//            String locationString = "[" + lat + "," + lon + "]";
            
            Intent intent = new Intent(WebMapActivity.this, NewExpenditureActivity.class);
            intent.putExtra("geoloc", geoloc);
            this.setResult(RESULT_OK, intent);
            nhSmsApp.setActivity(null);
            finish();
        } else if(view.getId() == R.id.back_btn){
        	nhSmsApp.setActivity(null);
            finish();
        }

    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 截获按键事件
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			nhSmsApp.setActivity(null);
			finish();
			System.gc();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

    private class JavaScriptInterface {
        public double keep_getLatitude() {
            if (mostRecentLocation == null)
                return 30.251442;
            else
                return mostRecentLocation.getLatitude();
        }

        public double keep_getLongitude() {
            if (mostRecentLocation == null)
                return 120.172950;
            else
                return mostRecentLocation.getLongitude();
        }

        public int keep_getScale() {
            return 18;
        }

        public void keep_logbyJs(String string) {
            Log.v("GOOGLE MAP", string);
        }

        public void keep_setLocation(String string) {
            Log.v("GOOGLE MAP--", string);
            if (string.equals("webview")) {
                flag = 0;
            } else if (flag < 1) {
                lat = Double.valueOf(string);
                flag++;
            } else if (flag == 1) {
                lon = Double.valueOf(string);
                new MyAsyncTask().execute(lat, lon);
            }
        }
    }

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // log it when the location changes
            if (location != null) {
                FileUtil.addLog("Location changed : Lat: " + location.getLatitude() + " Lng: " + location.getLongitude(), WebMapActivity.class, "WebMapActivity", null);
            }
        }

        public void onProviderDisabled(String provider) {
            // Provider被disable时触发此函数，比如GPS被关闭
        }

        public void onProviderEnabled(String provider) {
            // Provider被enable时触发此函数，比如GPS被打开
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        }
    };

    private class MyAsyncTask extends AsyncTask<Double, Object, Object> {
        @Override
        protected Object doInBackground(Double... objects) {
            String result = "";
            if (objects[0] == null)
                return result;
            Double latTemp = (Double) objects[0];
            Double lonTemp = (Double) objects[1];
            result = HttpUtil.getAddressInfo(latTemp+","+lonTemp);
            return result;
        }

        @Override
        protected void onPostExecute(Object o) {
            tip.setText(o.toString());
            tipTemp = o.toString();
            progressBar.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(LocationManager.NETWORK_PROVIDER)) {
            // 当GPS定位时，在这里注册requestLocationUpdates监听就非常重要而且必要。
            // 没有这句话，定位不能成功。
            if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                        locationListener);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 取消注册监听
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(locationListener);
        }
    }
}